package com.csp.main.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csp.common.utils.R;
import com.csp.main.entity.UserCommon;
import com.csp.main.entity.UserFans;
import com.csp.main.entity.UserFocus;
import com.csp.main.service.UserCommonService;
import com.csp.main.service.UserFansService;
import com.csp.main.service.UserFocusService;
import com.csp.main.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 粉丝 前端控制器
 * </p>
 *
 * @author csp
 * @since 2022-06-09
 */
@RestController
@RequestMapping("/main/user-fans")
public class UserFansController {

    @Autowired
    private UserFansService userFansService;

    @Autowired
    private UserFocusService userFocusService;

    @Autowired
    private UserCommonService userCommonService;

    @GetMapping("/list")
    public R list(HttpServletRequest request){
        String token = request.getHeader(JWTUtils.USER_LOGIN_TOKEN);
        String userId = JWTUtils.validateToken(token);

        QueryWrapper<UserFans> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<UserFans> list = userFansService.list(queryWrapper);
        return R.ok().data("rows",list);
    }

    @GetMapping("/add/{id}")
    public R add(HttpServletRequest request,@PathVariable String id){
        String token = request.getHeader(JWTUtils.USER_LOGIN_TOKEN);
        String fansId = JWTUtils.validateToken(token);

        QueryWrapper<UserFans> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fans_id",fansId);
        List<UserFans> list = userFansService.list(queryWrapper);
        if(list.isEmpty()){
            UserFans userFans = new UserFans();
            userFans.setFansId(fansId);
            userFans.setUserId(id);
            boolean save = userFansService.save(userFans);

            UserFocus userFocus = new UserFocus();
            userFocus.setUserId(fansId);
            userFocus.setFocusId(id);
            userFocusService.save(userFocus);

            UserCommon user1 = userCommonService.getById(id);
            user1.setFansNum(user1.getFansNum()+1);
            userCommonService.updateById(user1);
            UserCommon user2 = userCommonService.getById(fansId);
            user2.setFocusNum(user2.getFocusNum()+1);
            userCommonService.updateById(user2);
            return save?R.ok():R.error();
        }
        return R.error();
    }


}

